const { spawn } = require('child_process');
const {v4: uuid} = require('uuid');
// const file = require.resolve('./curl_cffi_passby_akamai.py');

function processFile(file, callback, ...args){
    const uid = uuid();
    const successSignalStart = uid + '_successSignalStart';
    const successSignalEnd = uid + '_successSignalEnd';
    const failureSignal = uid + '_failureSignal';
    const workerProcess = spawn('node',
        [file, successSignalStart, successSignalEnd, failureSignal].concat(args), {encoding: 'utf-8'});

    let needCallback = true;
    const errMsg = {"success":false, "msg":""};
    const inter = setInterval(() => {
        errMsg.msg = '验证超时';
        callBackAndKill(errMsg);
    }, 18000)

    function callBackAndKill(msg) {
        clearInterval(inter);
        needCallback = false;
        callback(JSON.stringify(msg));
        workerProcess.kill('SIGKILL');
    }
    let successText = '';
    let successTextSignal = 0;
    workerProcess.stdout.on('data', (data) => {
        const stdoutStr = data.toString();
        // console.log(stdoutStr);
        if (stdoutStr.indexOf(successSignalStart) !== -1) {
            successTextSignal = 1;
        }
        if (stdoutStr.indexOf(successSignalEnd) !== -1) {
            successTextSignal = 2;
        }
        if (successTextSignal === 1 || successTextSignal === 2){
            successText += stdoutStr;
        }
        if (successTextSignal === 2) {
            let matchStr = successText.match(`${successSignalStart}.*?(\\{.+})${successSignalEnd}`)[1];
            const msg = {"success":true, "data": JSON.parse(matchStr)};
            callBackAndKill(msg);
            successTextSignal = 0;
        } else if (stdoutStr.indexOf(failureSignal) !== -1) {
            const errStr = stdoutStr.match(`${failureSignal}.*?(\\{.+})`)[1];
            const errData = JSON.parse(errStr);
            errMsg.msg = errData.msg || errStr;
            callBackAndKill(errMsg);
        }
    });
    workerProcess.stderr.on('data', (data) => {
        const errStr = data.toString();
        if (errStr.indexOf("Debugger") < 0 && errStr.indexOf("debugger") < 0 && errStr.indexOf("Warning") < 0
        && errStr.indexOf("reportTime") < 0 // 兼容腾讯验证码的警告信息
        ) {
            errMsg.msg = '出现错误字符' + errStr;
            callBackAndKill(errMsg);
        }
    });
    workerProcess.on('close', (code) => {
        if (needCallback){
            callBackAndKill(errMsg);
        }
        clearInterval(inter);
    })
}


// async function processAkamaiPyFile(url, method, cookies, data, headers, log, traceId, productName, callback=null) {
//     log.info(`[${productName}][%s] curl_cffi_passby_akamai, %s请求中...`, traceId, url);
//     headers = JSON.stringify(headers);
//     const args = [file, url];
//     if (method){args.push('-m ' + method);}
//     if (cookies){args.push('-c ' + new Buffer.from(cookies, 'utf-8').toString('base64'));}
//     if (data){args.push('-d ' + new Buffer.from(data, 'utf-8').toString('base64'));}
//     if (headers){args.push( '-a ' + new Buffer.from(headers, 'utf-8').toString('base64'));}
//     const workerProcess = spawn('python3.7', args, {encoding: 'utf-8'});
//     let stdoutStr = '';
//     let errStr = '';
//
//     workerProcess.stdout.on('data', (data) => {
//         stdoutStr += data.toString();
//         // console.log(stdoutStr);
//     });
//     workerProcess.stderr.on('data', (data) => {
//         errStr += data.toString();
//     });
//     workerProcess.on('close', (code) => {
//         if (code === 1) {
//             // errorMsg = 'curl_cffi_passby_akamai.py执行失败';
//             log.warn(`[${productName}][%s] curl_cffi_passby_akamai, 执行失败: %s`, traceId, errStr);
//             callback(null);
//         }
//         if (callback) {
//             if (stdoutStr.length > 128){
//                 log.info(`[${productName}][%s] curl_cffi_passby_akamai, %s响应:%s`, traceId, url,
//                     stdoutStr.slice(0, 128)+'...');
//             }
//             else {
//                 log.info(`[${productName}][%s] curl_cffi_passby_akamai, %s响应:%s`, traceId, url, stdoutStr);
//             }
//             callback(JSON.parse(stdoutStr), url);
//         }
//     })
// }


module.exports = {
    processFile: processFile,
    // processAkamaiPyFile: processAkamaiPyFile,
}